<template>
  <div class="zs-table-page-container">
    <div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
      <span>
        <el-select :disabled="Boolean(projectName)" @change="getCardData" v-model="queryParams.biProjectCode" filterable
          class="zs-select-md zs-space-right-sm" placeholder="项目名称">
          <el-option v-for="item in projectList" :key="item.biProjectCode" :label="item.projectName"
            :value="item.biProjectCode" />
        </el-select>
        <el-date-picker @change="getCardData" class="zs-space-right-sm" v-model="queryParams.yearMonth" type="month"
          placeholder="日期" :clearable="false" value-format="YYYY-MM" :prefix-icon="DateBeforeIcon" />
        <el-select v-if="viewData.active == 1" @change="getCardData" v-model="queryParams.cardLabel" class="zs-select-md zs-space-right-sm"
          placeholder="口径">
          <el-option v-for="item in caliberList" :key="item.dictValue" :label="item.dictLabel"
            :value="item.dictValue" :disabled="['HOTEL','APARTMENT'].includes(bizType) && item.dictValue == '1'" />
        </el-select>
        <el-button @click="getCardData" class="zs-btn-plain">查询</el-button>
      </span>
      <span class="zs-layout-flex-row">
        <el-button class="zs-btn-plain" @click="handleDownload">
          <el-icon class="el-icon--left">
            <Upload />
          </el-icon>导出
        </el-button>
        <template v-if="isHaveView">
          <el-button v-for="item in viewData.type" :key="item.dictValue" @click="()=>{viewData.active = item.dictValue; getCardData()}"
            :class="[item.dictValue == viewData.active ? 'zs-btn-primary' : 'zs-btn-plain']" 
            v-btnPermi="{ permi:item.btnPermi, isHiden:true }"
          >{{ item.dictLabel }}</el-button>
        </template>
      </span>
    </div>
    <div class="zs-card zs-table-page-content">
      <div v-if="tableData.cardData.length > 0" class="card-box">
        <div v-for="item, index in tableData.cardData" :key="index" class="benchmarkingData-item zs-space-bottom"
          :class="{'isSelect':item.productCode == queryParams.productCode,'item-line': ['项目','租赁'].includes(item.productName) && viewData.active == 1 }" @click="()=>{queryParams.productCode = item.productCode;queryList()}">
          <div class="item-header">
            <span>{{ item.productName }}</span>
            <span class="line">|</span>
            <span>{{ item.subjectName }}</span>
          </div>
          <div class="item-main">
            <div class="main-text">
              <span class="title">{{ queryParams.cardLabel == '0' ? '累计预算' : '累计标准'}}</span>
              <div>
                <!-- :style="{ color: item.standard.indexOf('-') !== -1 ? '#FF0000' : '#333333' }"> -->
                <span class="val">
                  {{ formatArea(item.budgetAmount, 1) }}
                </span>
                <span style="font-size: 10px;">%</span>
              </div>
            </div>
            <div class="main-vs">
              <span>VS</span>
            </div>
            <div class="main-text">
              <span class="title">累计实际</span>
              <div>
                <span class="val" :class="{'zs-text-red':item.proportionFlag == 1,'zs-text-orange':item.proportionFlag == 2, 'zs-text-green':item.proportionFlag == 3}">{{ formatArea(item.actualAmount, 1) }}</span><span style="font-size: 10px;">%</span>
              </div>
            </div>
          </div>
          <div v-if="[3,4].includes(viewData.active)" class="item-footer" :style="{ 'background-color': item.productCode == queryParams.productCode ? '#6f97ff' : '#eef4fe' }">
            <div class="text-hide" v-if="viewData.active == 3" :title="item.peopleName">责任人：{{ item.peopleName || '无' }}</div>
            <div class="text-hide" v-if="viewData.active == 4" :title="item.region">区域：{{ item.region || '无' }}</div>
          </div>
          <!-- <div class="item-footer" :style="{ 'background-color': index == 0 ? '#ffffff' : '#eef4fe' }">
            <div class="footer-text-box">
              <span>预算</span>
              <span>{{ item.val }}万元</span>
            </div>
          </div> -->
        </div>
      </div>
      <hsTableV2 fixed rowKey="subjectNum" isTree :loading="tableData.loading" :columns="tableData.columns"
        :data="tableData.data" expandColumnKey="subjectNum" :headerHeight="72" isMultistageHeader :expendList="tableData.defaultExpendList"
        :multistageHeaderData="tableData.multistageData" :laststage="{ name: 'isfinal', val: 1 }" />
        <div class="zs-text-gray-dark zs-text-sm zs-space-top">*单位：万元</div>
      <!-- <hsTableV2 rowKey="subjectNum" :loading="tableData.loading" :columns="tableData.columns"
        :data="tableData.data" :headerHeight="72" isMultistageHeader :multistageHeaderData="tableData.multistageData" /> -->
      <!-- :expendList="tableData.defaultExpendList" -->
    </div>
  </div>
</template>

<script setup lang="jsx">
// import TableV2 from '@/components/tableV2.vue';
import dbPublicApi from '@/api/dbPublic'
import detailPagesApi from '@/api/Manage/Business/detailPages'
import { toThousands } from '@/utils/number-util'
import { downloadNewFile, listToTree, formatArea } from "@/utils/publicUtils"
import { reactive, ref, shallowRef, h, computed } from "vue"
import { useRoute } from 'vue-router'
const route = useRoute()
let { updateDate, tabPermi, biProjectCode, bizType, projectName, yearMonth, cardLabel } = route.query

const DateBeforeIcon = shallowRef({
  render () {
    return h('span', { style: { 'font-size': '12px' } }, '截至')
  },
})

let caliberList = [
    { dictLabel: '预实对标', dictValue: '0' },
    { dictLabel: '实际对标', dictValue: '1' },
    { dictLabel: '预算对标', dictValue: '2' },
  ]
  
let viewData = reactive({
  active:1,
  type:[
    { dictLabel: '按项目', dictValue: 1, btnPermi:'p_btn_901_jingyingxiangmu_xiangqing_twoandonepage_projecview' },
    { dictLabel: '按楼层', dictValue: 2, btnPermi:'p_btn_901_jingyingxiangmu_xiangqing_twoandonepage_floorview' },
    { dictLabel: '按区域', dictValue: 3, btnPermi:'p_btn_901_jingyingxiangmu_xiangqing_twoandonepage_managementview' },
    { dictLabel: '按人员', dictValue: 4, btnPermi:'p_btn_901_jingyingxiangmu_xiangqing_twoandonepage_renview' },
  ],
  cardApi:{
    1: detailPagesApi.queryTwoCalculateDetailCardApi,
    2: detailPagesApi.queryTwoCalculateDetailCardFloorViewApi,
    3: detailPagesApi.queryTwoCalculateDetailCardManageViewApi,
    4: detailPagesApi.queryTwoCalculateDetailCardPeopleViewApi,
  },
  listApi:{
    1: detailPagesApi.queryTwoCalculateDetailListApi,
    2: detailPagesApi.queryTwoCalculateDetailListFloorViewApi,
    3: detailPagesApi.queryTwoCalculateDetailListManageViewApi,
    4: detailPagesApi.queryTwoCalculateDetailListPeopleViewApi,
  },
  exportApi:{
    1: detailPagesApi.twoCalculateExportApi,
    2: detailPagesApi.twoCalculateExportFloorViewApi,
    3: detailPagesApi.twoCalculateExportManageViewApi,
    4: detailPagesApi.twoCalculateExportPeopleViewApi,
  }
})

// 查询条件
let queryParams = reactive({
  productCode: '',
  biProjectCode,
  yearMonth: yearMonth || '',
  cardLabel: cardLabel || '0'
})

// 项目下拉选
let projectList = ref([])
const getPorjectList = () => {
  dbPublicApi.queryProjectPcApi({ dataTime: updateDate, resourceKey: tabPermi }).then((res) => {
    if (res.data.code == 200) {
      projectList.value = res.data.data
      if (projectName && !projectList.value.some(el=>el.projectName == decodeURI(projectName))) {
        projectList.value.push({ projectName:decodeURI(projectName), biProjectCode })
      }
    }
  })
}
getPorjectList()

const celWidth = ref(0)
// 表格数据
let tableData = reactive({
  cardData: [],
  loading: false,
  data: [],
  columns: [
    { key: 'subjectNum', align: "left", title: '序号', width: 80, minWidth: 80, isHaveTitle: true },
    { key: 'subjectName', align: "left", title: '科目', isHaveTitle: true, width: 170, minWidth: 170, indentKey: "level", },
  ],
  defaultExpendList:[],
  multistageData: null,
})


async function queryList () {
  tableData.loading = true
  let res = await viewData.listApi[viewData.active](queryParams)
  let resData = res.data
  let defaultExpendList = []
  if (resData.code == 200 && resData.data) {
    queryParams.yearMonth == '' ? queryParams.yearMonth = resData.data.dataTime : ''
    tableData.data = listToTree(resData.data.dataList,'parentSubjectCode', 'subjectNum',null,(el)=>{
      if (viewData.active !== 1) defaultExpendList.push(el.subjectNum)
    })
    tableData.defaultExpendList = defaultExpendList
  } else {
    tableData.data = []
    tableData.defaultExpendList = []
  }
  initTableColumns()
  tableData.loading = false
}

async function getCardData () {
  let res = await viewData.cardApi[viewData.active](queryParams)
  let resData = res.data
  if (resData.code == 200) {
    tableData.cardData = resData.data
    if (resData.data.length > 0) {
      queryParams.productCode = resData.data[0]?.productCode
      queryList()
    } else {
      initTableColumns()
      tableData.data = []
    }
  }
}
getCardData()

// 格式化表格列及多级表头分组
function initTableColumns () {
  let windowWidth = document.documentElement.scrollWidth
  celWidth.value = (windowWidth - 136 - 250) / 9
  if (queryParams.yearMonth) {
    let curDate = queryParams.yearMonth.split('-')
    let curYear = curDate[0]
    let curMonth = Number(curDate[1])
    let headerArr = [
      { key: 'month', title: `${curYear}年${curMonth}月`, childrenIndex: [] },
      { key: 'cumulative', title: `${curYear}年1-${curMonth}月` },
      { key: 'year', title: `${curYear}年度`, childrenIndex: [] }
    ]
    let multistageData = {}
    let columns = []
    headerArr.forEach((el, index) => {
      let curStartIndex = index * 3 + 2
      multistageData[el.key] = {
        key: el.key,
        title: el.title,
        childrenIndex: [curStartIndex, curStartIndex + 1, curStartIndex + 2]
      }
      let curColumns = [
        { parentKey: el.key, key: `${el.key}Budget`, title: queryParams.cardLabel == 0 ? '预算值' : '标准值' },
        { parentKey: el.key, key: `${el.key}Actual`, title: queryParams.cardLabel == 2 ? '预算值' : '实际值' },
        { parentKey: el.key, key: `${el.key}Proportion`, title: queryParams.cardLabel == 0 ? '完成率' : '评价' },
      ]
      curColumns.forEach(ele => {
        columns.push({
          ...ele,
          align: 'right',
          width: celWidth.value > 80 ? celWidth.value : 80,
          minWidth: celWidth.value > 80 ? celWidth.value : 80,
          cellRenderer: ({ rowData }, emptyMark) => {
            if (rowData[ele.key]) {
              let curVal = rowData[ele.key]
              if (/^([\u4e00-\u9fa5]+)$/.test(curVal)) {
                let color = rowData[ele.key+'Flag']
                return <span class={{'zs-text-red':color == 1,'zs-text-orange':color == 2,'zs-text-green':color == 3}}>{curVal}</span>
              }
              if (queryParams.cardLabel == 0) {                
                let digit = rowData.subjectName.indexOf('率') > -1 && ele.key.indexOf('Proportion') == -1 ? 1 : 0
                curVal = toThousands(decimalRound(curVal.replace('%',''), digit))
                if (ele.key.indexOf('Proportion') > -1 || rowData.subjectName.indexOf('率') > -1){
                  curVal = curVal + '%'
                }
                if (ele.key.indexOf('Proportion') > -1) return <span>{ curVal }</span>
              } else {
                let curUnit = ele.key.indexOf('Budget') > -1 ? rowData.unit : (ele.key.indexOf('Actual') > -1 ? rowData.actualUnit : '')
                curVal = toThousands(curVal) + curUnit
              }
              let yuanVal = rowData[ele.key+'Yuan'] ? toThousands(rowData[ele.key+'Yuan']) + (rowData.yuanUnit || '') : ''
              return <ElTooltip content={yuanVal} placement="top">
                <span>{curVal}</span>
              </ElTooltip>
            } else {
              return <span>{emptyMark}</span>
            }
          }
        })
      })
    })
    tableData.multistageData = multistageData
    tableData.columns.splice(2, tableData.columns.length - 2, ...columns)
  } else {
    tableData.columns.splice(2, tableData.columns.length - 2, {key:'empty',title:'', width:celWidth.value * 9})
  }
}

function decimalRound(num, digit = 2) {
  let reg = /^-{0,1}(|\d*|(\d*\.\d*))$/;
  if(!reg.test(num) || digit < 0) return num
  if (digit == 0) return Math.round(num)
  const multiplier = Math.pow(10, digit);
  let roundedNum = Math.round(num * multiplier) / multiplier;
  let strNum = roundedNum.toString().split('.');
  if (strNum.length > 1 && strNum[1].length < digit) {
      strNum[1] += '0'.repeat(digit - strNum[1].length);
  } else if (strNum.length === 1) {
      strNum.push('0'.repeat(digit));
  }
  return strNum.join('.');
}

// 导出
const handleDownload = async () => {
  const fileName = `两算一控数据.xls`
  let fileData
  await viewData.exportApi[viewData.active](queryParams).then(res => {
    fileData = res.data
  })
  downloadNewFile(fileData, fileName)
}

let isHaveView = computed(()=>{
  if (bizType !== 'COMMERCIAL' || haveViewList.value.length == 0) return false
  let haveViewCodeList = haveViewList.value.map(el=>el.biCode)
  return haveViewCodeList.indexOf(queryParams.biProjectCode) > -1
})
let haveViewList = ref([])
function getIsHaveViewProject() {
  detailPagesApi.getHaveViewProjectListApi().then(res=>{
    let resData = res.data
    if(resData.code == 200){
      haveViewList.value = resData.data || []
    }
  })
}

if (bizType === 'COMMERCIAL') {
  console.log(isHaveView);
  getIsHaveViewProject()
}
</script>

<style lang="scss" scoped>
@font-face {
  font-family: 'DIN Alternate-Bold';
  src: url('/src/assets/fontIcon/DIN\ Alternate\ Bold.ttf');
}
.card-box{
  display:flex;
  flex-wrap: wrap;
    .isSelect {
    background-color: #477AFD;
    color: #FFFFFF;
  }
  .benchmarkingData-item{
    width: 204px;
    width:calc((100% - 80px) / 6);
    min-width: 167px;
    // height: 148px;
    border: 1px solid #eaeaea;
    border-radius: 6px;
    padding: 12px;
    margin-right: 16px;
    box-sizing: border-box;
    overflow: hidden;
    &:nth-child(6n){
      margin-right: 0;
    }
    .item-header{
      height: 24px;
      line-height: 24px;
      font-size: 16px;
      text-align: center;
      border-bottom: 1px solid #D4D8DF;
      padding-bottom: 8px;
      margin-bottom: 8px;
      .line{
        display: inline-block;
        margin: 0 10px;
      }
    }
    .item-main{
      display: flex;
      justify-content: space-between;
      margin-top:14px;
      // margin-bottom: 7px;
      .main-text{
        display: flex;
        flex-direction: column;
        width: calc((100% - 26px) / 2);
        text-align: center;
        .title{
          display: inline-block;
          height: 18px;
          line-height: 18px;
          font-size: 12px;
        }
        .val{
          // height:34px;
          line-height: 30px;
          font-size: 20px;
          font-weight: bold;
          font-family: DIN Alternate,DIN Alternate-Bold;
        }      
      }
      .main-vs{
        padding-top: 18px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin:0 6px;
        span{
          font-size: 12px;
          font-weight: bold;
          font-family: DIN Alternate,DIN Alternate-Bold;
        }
      }
    }
    .item-footer{
      display: flex;
      justify-content: center;
      border-radius: 6px;
      padding: 3px 12px;
      font-size: 12px;
      height: 18px;
      line-height: 18px;
      opacity: 0.8;
      .footer-text-box{
        width: 90%;
        display: flex;
        justify-content: space-between;
      }
      .text-hide{
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    // &:last-child{
    //   position: relative;
    //   overflow: initial;
    //   &::before{
    //     content:'';
    //     height: 120px;
    //     width: 1px;
    //     border-right: 1px solid blue;
    //     position: absolute;
    //     top: 0;
    //     left: -9px;
    //   }
    // }
  }
  .item-line{
    position: relative;
    overflow: initial;
    &::after{
      content:'';
      height: 120px;
      width: 1px;
      border-left: 1px solid #eaeaea;
      position: absolute;
      top: 0;
      right: -9px;
    }
  }
}
</style>
